﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Windows.Controls.Primitives;
using System.Diagnostics;

namespace SilverSmug
{
    public class Album
    {
        public string key { get; set; }
        public string id { get; set; }
        public string title { get; set; }
        public string categoryName { get; set; }
        public string categoryId { get; set; }
        private bool foundImages = false;
        private int imageCount = 0;
        private AlbumFinishedCB finishedProcCB;

        public List<SMImage> imageList;

        public Album()
        {
            imageList = new List<SMImage>();
        }

        public delegate void AlbumFinishedCB();

        public void retrieveImages(AlbumFinishedCB cb)
        {
            finishedProcCB = cb;
            String getImagesUrl = SmugAcc.makeRequestURL(SmugAcc.getImagesMethod,
                            "SessionID=" + SmugAcc.sessionID, "AlbumID=" + id, "AlbumKey=" + key);
            SmugAcc.sendRequest(getImagesUrl, parseImages);
        }

        private void parseImages(XDocument xDoc)
        {
            String error = SmugAcc.checkForError(xDoc);
            if (error != "")
            {
                //need error message here MyText.Text = "Error:\n" + error;
                return;
            }
            var images = from image in xDoc.Descendants("Image")
                         where image.Attribute("id") != null
                         where image.Attribute("Key") != null
                         select new SMImage
                         {
                             id = (string)image.Attribute("id").Value,
                             key = (string)image.Attribute("Key").Value
                         };

            foreach (SMImage i in images)
            {
                imageList.Add(i);
            }

            //For safety, these need to be done in separate loops
            int u = 0;
            foreach (SMImage i in imageList)
            {
                i.retrieveURL(delegate()
                {
                    if (++imageCount == imageList.Count)
                    {
                        if (imageList.First().url == null)
                            Debug.WriteLine("Cannot get url for: " + title + " image " + imageList.First().id);
                        finishedProcCB();
                    }
                });
            }
            foundImages = true;
        }       

        public List<SMImage> getImages()
        {
            return imageList;
        }

        
    }
}
